package com.ai.platform.core.security;

import com.ai.platform.model.dto.Output;
import com.ai.platform.core.service.IControlService;
import com.ai.platform.system.entity.SysPermission;
import com.ai.platform.system.entity.SysRole;
import com.ai.platform.system.entity.SysUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * Created by yeyingsheng on 2018/4/2.
 */
public class AiShiroRealm extends AuthorizingRealm {

    @Autowired
    private IControlService iControlService;

    protected static final Logger logger = LoggerFactory.getLogger(AiShiroRealm.class);

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        logger.info("======用户授权认证======");
        SysUser sysUser= (SysUser) principals.getPrimaryPrincipal();
        if(null!=sysUser){
            //角色查询
            Output  output=iControlService.execute("sysRoleServiceImpl","queryRoleByUserId",true,"userId",sysUser.getId().toString());
            List<SysRole> roles= (List<SysRole>) output.getData();
            //添加角色和权限
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            if(!CollectionUtils.isEmpty(roles)) {
                for (SysRole sysRole : roles) {
                    simpleAuthorizationInfo.addRole(sysRole.getId().toString());
                    //添加权限
                    output = iControlService.execute("sysPermissionServiceImpl", "queryPermissionByRoleId",true, "roleId", sysRole.getId().toString());
                    List<SysPermission> sysPermissionList = (List<SysPermission>) output.getData();
                    if(!CollectionUtils.isEmpty(sysPermissionList)) {
                        for (SysPermission permission : sysPermissionList) {
                            simpleAuthorizationInfo.addStringPermission(permission.getModule()+"::"+permission.getPrivilege());
                        }
                    }
                }
            }
            return simpleAuthorizationInfo;

        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        logger.info("======用户登陆认证======");
        //加这一步的目的是在Post请求的时候会先进认证，然后在到请求
        if (token.getPrincipal() == null) {
            return null;
        }
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        //获取用户信息
        String account = usernamePasswordToken.getUsername();
        Output output=iControlService.execute("sysUserServiceImpl","getSysUserByAccount",true,"account",account);
        SysUser sysUser= (SysUser) output.getData();
        if (sysUser == null) {
            //这里返回后会报出对应异常
            return null;
        } else {
            //盐值
            ByteSource credentialsSalt = ByteSource.Util.bytes(sysUser.getSalt());
            //这里验证authenticationToken和simpleAuthenticationInfo的信息
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(sysUser, usernamePasswordToken.getPassword(),credentialsSalt, getName());
            return simpleAuthenticationInfo;
        }
    }
}
